package com.xpsoft.oa.service.admin.impl;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.admin.AdminExpensesDao;
import com.xpsoft.oa.dao.admin.AdminExpensesInfoDao;
import com.xpsoft.oa.model.admin.AdminExpenses;
import com.xpsoft.oa.model.admin.AdminExpensesInfo;
import com.xpsoft.oa.model.system.FileAttach;
import com.xpsoft.oa.service.admin.AdminExpensesService;
import com.xpsoft.oa.service.system.FileAttachService;

public class AdminExpensesServiceImpl extends BaseServiceImpl<AdminExpenses> implements AdminExpensesService{
	private AdminExpensesDao dao;
	@Autowired
	private FileAttachService fileAttachService;
	@Autowired
	private AdminExpensesInfoDao adminExpensesInfoDao;
	public AdminExpensesServiceImpl(AdminExpensesDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveAdminExpenses(AdminExpenses adminExpenses, String dataList) {
		Boolean isNew = true;//新增标志
		if(adminExpenses.getId()!=null){
			isNew = false;
		}
		dao.save(adminExpenses);
		if(StringUtils.isNotBlank(dataList)){
			List<AdminExpensesInfo> adminExpensesInfoList = JsonUtil.fromJsonTypesWithDate(dataList,
					new TypeToken<List<AdminExpensesInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(AdminExpensesInfo adminExpensesInfo:adminExpensesInfoList){
					if(adminExpensesInfo.getId()!=null){//修改的记录
						idList.add(adminExpensesInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					adminExpensesInfoDao.deleteAdminExpensesInfos(adminExpenses.getId(), idList);
				}
			}
			for(AdminExpensesInfo adminExpensesInfo:adminExpensesInfoList){
				adminExpensesInfo.setAdminExpenses(adminExpenses);
				if(StringUtils.isNotBlank(adminExpensesInfo.getFileIds())){
					Set<FileAttach> fileSet = new HashSet<FileAttach>();
					String fileIds[] = adminExpensesInfo.getFileIds().split("\\|");
					adminExpensesInfo.getFileAttachs().clear();
					for(String fileId:fileIds){
						fileSet.add(fileAttachService.get(Long.valueOf(fileId)));
					}
					adminExpensesInfo.getFileAttachs().addAll(fileSet);
				}
				adminExpensesInfoDao.save(adminExpensesInfo);
			}
		}
	}

}